﻿<%@ WebHandler Language="C#" Class="imgup" %>

using System;
using System.Web;
using Newtonsoft.Json;
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
using System.Web.Configuration;
using Models;
using System.Text;
using System.Drawing;

public class imgup : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.ContentEncoding = Encoding.UTF8;
        if (context.Request["REQUEST_METHOD"] == "OPTIONS")
        {
            context.Response.End();
        }
        SaveFile();
    }

    /// <summary>
    /// 文件保存操作
    /// </summary>
    /// <param name="basePath"></param>
    private void SaveFile(string basePath = "/upload/")
    {
        string _datePath = DateTime.Now.ToString("yyyyMMdd") + "/";
        basePath += _datePath;

        string serverPath = "~" + basePath;
        var name = string.Empty;
        serverPath = (serverPath.IndexOf("~") > -1) ? System.Web.HttpContext.Current.Server.MapPath(serverPath) :
        serverPath;
        HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
        //    var file = HttpContext.Request.Form.Files[0];


        if (!Directory.Exists(serverPath))
            Directory.CreateDirectory(serverPath);


        //var suffix = files[0].ContentType.Split('/');
        //var _suffix = suffix[1];
        //var _temp = System.Web.HttpContext.Current.Request["name"];

        //if (!string.IsNullOrEmpty(_temp))
        //{
        //    name = _temp;
        //}
        //else
        //{
        Random rand = new Random(24 * (int)DateTime.Now.Ticks);
        var ranNumber = rand.Next();
        name = ranNumber + ".jpg";
        //}

        if (!string.IsNullOrEmpty(HttpContext.Current.Request["_name"]) && HttpContext.Current.Request["_name"] != "null")
            ranNumber = int.Parse(HttpContext.Current.Request["_name"]);
        var _base64 = System.Web.HttpContext.Current.Request["_base64"];
        //if (!string.IsNullOrEmpty(_base64))
        //{
        //    makeThumb = Base64StrToImage(_base64, serverPath, ranNumber.ToString());
        //}
        //else
        //{
        var full = serverPath + name;
        files[0].SaveAs(full);

        MakeThumbnail1(serverPath, serverPath.Replace("upload", "Up"),name, 200, 200, "W");
        //}

        var filepath = basePath.Replace("upload", "Up") + name;
        var msg = ranNumber;
        var code = 1;

        // System.Web.HttpContext.Current.Response.Write(_result);

        System.Web.HttpContext.Current.Response.Write(JsonConvert.SerializeObject(new { code,msg,filepath}));

    }

    /// <summary>
    /// 将Base64字符串转换为图片并保存到本地
    /// </summary>
    /// <param name="base64Str">base64字符串</param>
    /// <param name="savePath">图片保存地址，如：/dis/Images/10000.png</param>
    /// <returns></returns>
    public static string Base64StrToImage(string base64Str, string serverPath, string name)
    {
        var ret = "";
        try
        {
            serverPath = serverPath.Replace("Up", "upload");

            if (!Directory.Exists(serverPath))
                Directory.CreateDirectory(serverPath);

            var base64 = base64Str;//System.Web.HttpContext.Current.Request["_base64"];
            base64 = base64.Replace("data:image/png;base64,", "").Replace("data:image/jgp;base64,", "").Replace("data:image/jpg;base64,", "").Replace("data:image/jpeg;base64,", "");//将base64头部信息替换
            byte[] bytes = Convert.FromBase64String(base64);
            MemoryStream memStream = new MemoryStream(bytes);
            Image mImage = Image.FromStream(memStream);

            Bitmap bp = new Bitmap(mImage);
            MemoryStream ms = new MemoryStream();

            bp.Save(serverPath + name + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
            ms.Close();
            bp.Dispose();
            ret = serverPath + name + ".jpg";
        }
        catch (Exception ex)
        {
            ret = "";
        }
        return ret;
    }

    #region 缩略图
    /// <summary>
    /// 生成缩略图
    /// </summary>
    /// <param name="originalImagePath">源图路径（物理路径）</param>
    /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
    /// <param name="width">缩略图宽度</param>
    /// <param name="height">缩略图高度</param>
    /// <param name="mode">生成缩略图的方式</param>    
    public static void MakeThumbnail1(string originalImagePath, string thumbnailPath, string filename, int width, int height, string mode)
    {
        System.Drawing.Image originalImage = System.Drawing.Image.FromFile(originalImagePath + filename);

        int towidth = originalImage.Width > width ? width : originalImage.Width;
        int toheight = originalImage.Height > height ? height : originalImage.Height;

        int x = 0;
        int y = 0;
        int ow = originalImage.Width;
        int oh = originalImage.Height;

        switch (mode)
        {
            case "HW":  //指定高宽缩放（可能变形）                
                break;
            case "W":   //指定宽，高按比例                    
                toheight = originalImage.Height * width / originalImage.Width;
                toheight = toheight > originalImage.Height ? originalImage.Height : toheight;
                break;
            case "H":   //指定高，宽按比例
                towidth = originalImage.Width * height / originalImage.Height;
                towidth = towidth > originalImage.Width ? originalImage.Width : towidth;
                break;
            case "Cut": //指定高宽裁减（不变形）                
                if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight)
                {
                    oh = originalImage.Height;
                    ow = originalImage.Height * towidth / toheight;
                    y = 0;
                    x = (originalImage.Width - ow) / 2;
                }
                else
                {
                    ow = originalImage.Width;
                    oh = originalImage.Width * height / towidth;
                    x = 0;
                    y = (originalImage.Height - oh) / 2;
                }
                break;
            default:
                break;
        }

        //新建一个bmp图片
        System.Drawing.Image bitmap = new System.Drawing.Bitmap(towidth, toheight);

        //新建一个画板
        System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);

        //设置高质量插值法
        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;

        //设置高质量,低速度呈现平滑程度
        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;

        //清空画布并以透明背景色填充
        g.Clear(System.Drawing.Color.Transparent);

        //在指定位置并且按指定大小绘制原图片的指定部分
        g.DrawImage(originalImage, new System.Drawing.Rectangle(0, 0, towidth, toheight), new System.Drawing.Rectangle(x, y, ow, oh), System.Drawing.GraphicsUnit.Pixel);

        try
        {
            //检查是否有该路径没有就创建
            if (!Directory.Exists(thumbnailPath))
            {
                Directory.CreateDirectory(thumbnailPath);
            }
            //以jpg格式保存缩略图
            bitmap.Save(thumbnailPath + filename, System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (System.Exception e)
        {
            throw e;
        }
        finally
        {
            originalImage.Dispose();
            bitmap.Dispose();
            g.Dispose();
        }
    }
    #endregion

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}